package com.concurrency.example.singleton;

import com.concurrency.annoations.NotThreadSafe;

/**
 * 懒汉模式 双重检查锁
 */
@NotThreadSafe
public class SingletonExample {

    private static SingletonExample instance = null;

    private SingletonExample(){}

    // 对象初始化在内存中的步骤
    //1、memory = allocate()  分配对象的内存空间
    //2、ctorInstanche()      初始化对象
    //3、instance = memory    设置instance指向刚分配的内存


    //jvm和cpu指令优化发生指令重排
    //1、memory = allocate()  分配对象的内存空间
    //2、instance = memory    设置instance指向刚分配的内存
    //3、ctorInstanche()      初始化对象

    public static synchronized SingletonExample getInstance(){
        if(instance == null){         //这里可能有问题
            synchronized (SingletonExample.class){
                if(instance == null){
                    instance = new SingletonExample();
                }
            }
        }
        return instance;
    }

}
